<template>
  <div class="transfer-seat-selector">
    <div class="route-summary">
      <el-card>
        <div class="route-info">
          <div class="segment">
            <el-tag type="primary" size="small">第一段</el-tag>
            <span class="train-info">{{ transferRoute.firstTrain.trainNumber }} {{ transferRoute.firstTrain.startStationName }} → {{ transferRoute.firstTrain.endStationName }}</span>
          </div>
          <div class="segment">
            <el-tag type="success" size="small">第二段</el-tag>
            <span class="train-info">{{ transferRoute.secondTrain.trainNumber }} {{ transferRoute.secondTrain.startStationName }} → {{ transferRoute.secondTrain.endStationName }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <el-steps :active="currentStep" align-center class="steps">
      <el-step title="选择第一段座位" />
      <el-step title="选择第二段座位" />
      <el-step title="确认购买" />
    </el-steps>

    <!-- 第一段座位选择 -->
    <div v-if="currentStep === 0" class="seat-selection">
      <h3>第一段：{{ transferRoute.firstTrain.trainNumber }} ({{ transferRoute.firstTrain.startStationName }} → {{ transferRoute.firstTrain.endStationName }})</h3>
      <seat-selector
        :train="transferRoute.firstTrain"
        :start-station-id="startStationId"
        :end-station-id="transferRoute.transferStationId"
        @seat-selected="handleFirstSeatSelected"
      />
    </div>

    <!-- 第二段座位选择 -->
    <div v-if="currentStep === 1" class="seat-selection">
      <h3>第二段：{{ transferRoute.secondTrain.trainNumber }} ({{ transferRoute.secondTrain.startStationName }} → {{ transferRoute.secondTrain.endStationName }})</h3>
      <div class="selected-first-seat" v-if="selectedFirstSeat">
        <el-alert
          :title="`已选择第一段座位：${selectedFirstSeat.carriageNumber}车厢${selectedFirstSeat.seatNumber}座 ¥${selectedFirstSeat.price}`"
          type="success"
          :closable="false"
        />
      </div>
      <seat-selector
        :train="transferRoute.secondTrain"
        :start-station-id="transferRoute.transferStationId"
        :end-station-id="endStationId"
        @seat-selected="handleSecondSeatSelected"
      />
    </div>

    <!-- 确认购买 -->
    <div v-if="currentStep === 2" class="purchase-confirmation">
      <h3>确认换乘票务信息</h3>
      <div class="selected-seats-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="第一段车次">{{ transferRoute.firstTrain.trainNumber }}</el-descriptions-item>
          <el-descriptions-item label="第一段座位">{{ selectedFirstSeat?.carriageNumber }}车厢{{ selectedFirstSeat?.seatNumber }}座</el-descriptions-item>
          <el-descriptions-item label="第一段价格">¥{{ selectedFirstSeat?.price }}</el-descriptions-item>
          <el-descriptions-item label="第二段车次">{{ transferRoute.secondTrain.trainNumber }}</el-descriptions-item>
          <el-descriptions-item label="第二段座位">{{ selectedSecondSeat?.carriageNumber }}车厢{{ selectedSecondSeat?.seatNumber }}座</el-descriptions-item>
          <el-descriptions-item label="第二段价格">¥{{ selectedSecondSeat?.price }}</el-descriptions-item>
          <el-descriptions-item label="总价格">¥{{ totalPrice }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="passenger-form">
        <el-form :model="passengerForm" :rules="passengerRules" ref="passengerFormRef" label-width="100px">
          <el-form-item label="乘车人姓名" prop="passengerName">
            <el-input v-model="passengerForm.passengerName" placeholder="请输入乘车人姓名" />
          </el-form-item>
          <el-form-item label="身份证号" prop="passengerIdCard">
            <el-input v-model="passengerForm.passengerIdCard" placeholder="请输入身份证号" />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="actions">
      <el-button v-if="currentStep > 0" @click="prevStep">上一步</el-button>
      <el-button v-if="currentStep < 2" type="primary" @click="nextStep" :disabled="!canNextStep">下一步</el-button>
      <el-button v-if="currentStep === 2" type="primary" @click="confirmPurchase" :loading="purchasing">确认购买</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { TransferRoute, Seat } from '@/types/train'
import SeatSelector from './SeatSelector.vue'

interface Props {
  transferRoute: TransferRoute
  startStationId: number
  endStationId: number
}

defineProps<Props>()

const emit = defineEmits<{
  seatSelected: [firstSeat: Seat, secondSeat: Seat, passengerInfo: { passengerName: string; passengerIdCard: string }]
}>()

const currentStep = ref(0)
const selectedFirstSeat = ref<Seat | null>(null)
const selectedSecondSeat = ref<Seat | null>(null)
const purchasing = ref(false)
const passengerFormRef = ref()

const passengerForm = reactive({
  passengerName: '',
  passengerIdCard: ''
})

const passengerRules = {
  passengerName: [
    { required: true, message: '请输入乘车人姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在2到50个字符', trigger: 'blur' }
  ],
  passengerIdCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ]
}

const totalPrice = computed(() => {
  if (selectedFirstSeat.value && selectedSecondSeat.value) {
    return selectedFirstSeat.value.price + selectedSecondSeat.value.price
  }
  return 0
})

const canNextStep = computed(() => {
  if (currentStep.value === 0) {
    return selectedFirstSeat.value !== null
  }
  if (currentStep.value === 1) {
    return selectedSecondSeat.value !== null
  }
  return false
})

const handleFirstSeatSelected = (seat: Seat) => {
  selectedFirstSeat.value = seat
}

const handleSecondSeatSelected = (seat: Seat) => {
  selectedSecondSeat.value = seat
}

const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const nextStep = () => {
  if (currentStep.value < 2 && canNextStep.value) {
    currentStep.value++
  }
}

const confirmPurchase = async () => {
  if (!selectedFirstSeat.value || !selectedSecondSeat.value) {
    ElMessage.error('请选择座位')
    return
  }

  try {
    const valid = await passengerFormRef.value.validate()
    if (!valid) return

    purchasing.value = true

    emit('seatSelected', selectedFirstSeat.value, selectedSecondSeat.value, {
      passengerName: passengerForm.passengerName,
      passengerIdCard: passengerForm.passengerIdCard
    })

  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    purchasing.value = false
  }
}
</script>

<style scoped>
.transfer-seat-selector {
  padding: 20px;
}

.route-summary {
  margin-bottom: 20px;
}

.route-info {
  display: flex;
  gap: 20px;
  align-items: center;
}

.segment {
  display: flex;
  align-items: center;
  gap: 10px;
}

.train-info {
  font-weight: 500;
}

.steps {
  margin: 30px 0;
}

.seat-selection {
  margin: 20px 0;
}

.seat-selection h3 {
  margin-bottom: 15px;
  color: #303133;
}

.selected-first-seat {
  margin-bottom: 15px;
}

.purchase-confirmation {
  margin: 20px 0;
}

.purchase-confirmation h3 {
  margin-bottom: 15px;
  color: #303133;
}

.selected-seats-info {
  margin-bottom: 20px;
}

.passenger-form {
  max-width: 400px;
}

.actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
}
</style>